package com.example.mymnue;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.util.ArrayList;
import java.util.List;

public class CaidanDBManager {
    private static final String TAG= "AA";
    private ShopDB shopDB;
    private String taname;

    public CaidanDBManager(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            shopDB=new ShopDB(context);
        }
        taname=ShopDB.TB_NAME;

    }
    public void add(CaidanItem item){
        SQLiteDatabase sd=shopDB.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("data",item.getDdata());
        values.put("time",item.getDtime());
        values.put("title",item.getDtitle());
        values.put("detail",item.getDdtail());
        sd.insert(taname,null,values);
        sd.close();
    }
    public void delete(int id){
        SQLiteDatabase sd=shopDB.getWritableDatabase();
        sd.delete(taname,"ID=?",new String[]{String.valueOf(id)});
        sd.close();
    }


    public List<CaidanItem> list(){
        List<CaidanItem> dlist=null;
        SQLiteDatabase sd=shopDB.getWritableDatabase();
        Cursor cursor=sd.query(taname,null,null,null,null,null,null);
        if (cursor!=null){
            dlist=new ArrayList<CaidanItem>();
            while (cursor.moveToNext()){
                CaidanItem item=new CaidanItem();
                item.setDdata(cursor.getString(cursor.getColumnIndexOrThrow("DATA")));
                item.setDtime(cursor.getString(cursor.getColumnIndexOrThrow("TIME")));
                item.setDtitle(cursor.getString(cursor.getColumnIndexOrThrow("TITLE")));
                item.setDdtail(cursor.getString(cursor.getColumnIndexOrThrow("DETAIL")));
                Log.i(TAG, "list: item="+item);
                dlist.add(item);
            }
            cursor.close();
        }
        sd.close();
        return dlist;
    }

}
